package com.applet.system.service.impl;

import java.util.List;

import com.applet.system.entity.BusinessException;
import com.applet.system.entity.dto.RoleDto;
import com.applet.system.mapper.RoleMapper;
import com.applet.system.service.RoleService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import com.applet.system.entity.Role;
import com.applet.system.service.UserService;

import javax.annotation.Resource;

@Service
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleMapper roleMapper;
	
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	
	@Override
	public List<Role> getPage(Role role) {
		return this.roleMapper.getPage(role);
	}

	@Override
	public int delete(List<Long> ids) throws BusinessException {
		for (int i = 0; i < ids.size(); i++) {
			if (this.userServiceImpl.getRoleIsUsed(ids.get(i))) {
				throw new BusinessException("角色ID:{}正在被使用,请移除相关配置后重试", ids.get(i));
			}
		}
		return this.roleMapper.delete(ids);
	}

	@Override
	public int add(Role role) {
		if (this.roleMapper.getIsRoleNameExist(role.getName(), null)) {
			throw new BusinessException("角色名称已存在,请勿重复录入", role.getName()); 
		}
		return this.roleMapper.add(role);
	}

	@Override
	public int update(Role role) {
		if (this.roleMapper.getIsRoleNameExist(role.getName(), role.getId())) {
			throw new BusinessException("角色名称已存在,请勿重复录入", role.getName()); 
		}
		return this.roleMapper.update(role);
	}

	@Override
	public Role getRoleById(Long roleId) {
		return this.roleMapper.getRoleById(roleId);
	}

	@Override
	public List<Long> getMenuIds(Long roleId) {
		return this.roleMapper.getMenuIds(roleId);
	}

	@Override
	public List<Long> getActionIds(Long roleId) {
		return this.roleMapper.getActionIds(roleId);
	}

	@Override
	public void authorize(RoleDto role) {
		// 删除之前的权限
		this.roleMapper.deleteRoleAuth(role.getId());
		if ((role.getActionIds() != null && !role.getActionIds().isEmpty()) || (role.getMenuIds() != null && !role.getMenuIds().isEmpty())) {
			// 录入新的权限
			this.roleMapper.insertRoleAuth(role);
		}
		// 查询涉及到的用户 清空他们的redis权限缓存
		List<Long> userIds = this.userServiceImpl.getUserIdsByRoleId(role.getId());
		for (Long userId : userIds) {
	    	String url_key = "console:user:resource:url:" + userId;
	    	String code_key = "console:user:resource:code:" + userId;
	    	this.stringRedisTemplate.delete(url_key);
	    	this.stringRedisTemplate.delete(code_key);
		}
	}

	@Override
	public List<Role> getAll() {
		return this.roleMapper.getAll();
	}

}
